let app = getApp()
let dealtype
let flag

Page({
  data: {
    dealtype: 'add',
    address: {}
  },
  onLoad: function (options) {
    if (options.type) {
      dealtype = options.type
      if (dealtype === 'edit') {
        wx.setNavigationBarTitle({
          title: '编辑地址'
        })
      } else {
        wx.setNavigationBarTitle({
          title: '新增地址'
        })
      }
    }
    var address = {
      "CITYNAME": "",
      "CITYID": "",
      "RECEIVERMOBILE": "",
      "TOWNNAME": "",
      "RECEIVERNAME": "",
      "ISDEFAULT": "1",
      "TOWNID": "",
      "PROVINCENAME": "",
      "COUNTYNAME": "",
      "ADDRESS": "",
      "USERID": "",
      "LABEL": "公司",
      "PROVINCEID": "",
      "COUNTYID": "",
      "DETAILADDRESS": "",
      "LOCATION": ""
    }
    if (options.address) {
      address = JSON.parse(decodeURIComponent(options.address))
    }
    this.setData({
      dealtype: dealtype,
      address: address
    })
    this.getCity()
  },
  onShow: function () {
    this.setData({
      showModel: false
    })
  },
  setIsDefault: function () {
    var address = this.data.address
    if (address.ISDEFAULT === '1') {
      address.ISDEFAULT = '0'
    } else {
      address.ISDEFAULT = '1'
    }
    this.setData({address: address})
  },
  checkInput: function (e) {
    var itype = e.currentTarget.dataset.inputtype
    var address = this.data.address
    if (itype === 'name') {
      address.RECEIVERNAME = e.detail.value
    } else if (itype === 'phone') {
      address.RECEIVERMOBILE = e.detail.value
    } else if (itype === 'detail') {
      address.DETAILADDRESS = e.detail.value
    }
    this.setData({
      address: address
    })
  },
  openMap: function () {
    var that = this
    wx.chooseLocation({
      success: function (res) {
        var address = that.data.address
        address.ADDRESS = res.address
        address.LOCATION = {
          lat: res.latitude,
          lng: res.longitude
        }
        that.setData({
          address: address
        })
      },
      fail: function (res) {
        that.checkLocationAuthor()
      }
    })
  },
  setAddressType: function (e) {
    var addrtype = e.currentTarget.dataset.addrtype
    var address = this.data.address
    address.LABEL = addrtype
    this.setData({
      address: address
    })
  },
  checkLocationAuthor: function () {
    var that = this
    wx.getSetting({
      success: (res) => {
        //非初始化进入该页面,且未授权
        if (res.authSetting['scope.userLocation'] !== undefined && res.authSetting['scope.userLocation'] !== true) {
          that.setData({
            showModel: true
          })
        } else if (res.authSetting['scope.userLocation'] === undefined) {//初始化进入
        }
      }
    })
  },
  getCity: function () {
    app.get('/yuanmai_we/address/cityList').then(res => {
      var address = this.data.address
      var city = []
      var cityid = []
      var curindex = 0
      for (var i = 0; i < res.length; i++) {
        city.push(res[i].CITYNAME)
        cityid.push(res[i].ID)
        if (res[i].ID === this.data.address.CITYID) {
          curindex = i
          break
        }
      }
      address.CITYNAME = city[curindex]
      address.CITYID = cityid[curindex]
      this.setData({
        cityindex: curindex,
        citys: city,
        citysid: cityid,
        address: address
      })
      flag = 0
      this.getArea(flag)
    })
  },
  addressChange: function (e) {
    var ptype = e.currentTarget.dataset.picktype
    if (ptype === 'city') {
      var cityindex = e.detail.value
      var address = this.data.address
      address.CITYNAME = this.data.citys[cityindex]
      address.CITYID = this.data.citysid[cityindex]
      address.COUNTYID = this.data.areainfos[cityindex][0].ID
      address.COUNTYNAME = this.data.areas[cityindex][0]
      this.setData({
        cityindex: cityindex,
        areaindex: 0,
        address: address
      })
    } else {
      var areaindex = e.detail.value
      var address = this.data.address
      address.COUNTYNAME = this.data.areas[this.data.cityindex][areaindex]
      address.COUNTYID = this.data.areainfos[this.data.cityindex][areaindex].ID
      this.setData({
        areaindex: areaindex,
        address: address
      })
    }
  },
  getArea: function (cityindex) {
    if (cityindex >= this.data.citysid.length) {
      if (this.data.address.COUNTYID === '') {
        var address = this.data.address
        address.COUNTYID = this.data.areainfos[this.data.cityindex][0].ID
        address.COUNTYNAME = this.data.areas[this.data.cityindex][0].COUNTYNAME
        this.setData({
          address: address,
          areaindex: 0
        })
      }
      return
    }
    var url = '/yuanmai_we/address/countyList/' + this.data.citysid[cityindex]
    app.get(url).then(this.chooseAreaCallBack.bind(this))
  },
  chooseAreaCallBack: function (res) {
    var address = this.data.address
    var area = []
    var areainfos = []
    if (this.data.areas != null && this.data.areas !== undefined) {
      area = this.data.areas
    }
    if (this.data.areainfos != null && this.data.areainfos !== undefined) {
      areainfos = this.data.areainfos
    }
    var temp_area_item = []
    var temp_area_item_infos = []
    for (var i = 0; i < res.length; i++) {
      if (res[i].CITYID === this.data.address.CITYID && res[i].ID === this.data.address.COUNTYID) {
        this.setData({
          areaindex: i
        })
      }
      temp_area_item.push(res[i].COUNTYNAME)
      temp_area_item_infos.push(res[i])
    }

    area.push(temp_area_item)
    areainfos.push(temp_area_item_infos)

    this.setData({
      areas: area,
      areainfos: areainfos
    })
    flag++
    this.getArea(flag)
  },
  addNewAddress: function () {
    var address = this.data.address
    var errMsg

    if (address.RECEIVERNAME === '') {
      errMsg = '请填写您的姓名'
    } else if (address.RECEIVERMOBILE === '') {
      errMsg = '请填写您的手机号'
    } else if (!/^1[3456789]\d{9}$/.test(address.RECEIVERMOBILE)) {
      errMsg = '手机号格式错误'
    } else if (address.CITYID === '') {
      errMsg = '请选择城市'
    } else if (!address.COUNTYNAME) {
      errMsg = '请选择行政区'
    } else if (address.ADDRESS === '') {
      errMsg = '请填写收货地址'
    } else if (address.DETAILADDRESS === '') {
      errMsg = '请填写详细地址'
    }

    if (errMsg) {
      app.toast.error(errMsg, 2000, '../../imgs/tips.png')
      return
    }

    var url = '/yuanmai_we/usercenter/address/update'
    var needHeader = true
    if (dealtype !== 'edit') {
      url = '/yuanmai_we/usercenter/address/add'
      needHeader = true
    }
    if (address.USERID === '') {
      address.USERID = app.globalData.userid
    }
    if (address.LOCATION.lat != null && address.LOCATION.lat !== undefined) {
      address.LOCATION = JSON.stringify(address.LOCATION)
    }
    address.coordinates = 'GCJ-02'
    address.__zaofans = true
    app.request(url, address).then(this.addNewAddressCallBack.bind(this))
    app.showLoading()
  },
  addNewAddressCallBack: function (res) {
    app.hideLoading()
    //---更新缓存地址----
    app.globalData.canReqAddress = true
    app.getAddress()

    wx.hideToast()
    wx.navigateBack()
  },
  deleteAddress: function () {
    var url = '/yuanmai_we/usercenter/address/delete'
    var addressid = this.data.address.ID
    var params = {
      ID: addressid,
      __zaofans: true
    }
    wx.showModal({
      title: '提示',
      content: '确定要删除该地址吗?',
      success: (res) => {
        if (res.confirm) {
          app.request(url, params).then(this.deleteAddressCallBack.bind(this))
          app.showLoading()
        }
      }
    })
  },
  deleteAddressCallBack: function (res) {
    app.hideLoading()
    //---更新缓存地址----
    app.globalData.canReqAddress = true
    app.getAddress()

    wx.hideToast()
    wx.navigateBack()
  }
})
